/**
* Copyright (C) 2021 All rights reserved.
*
* @file main.h
* @author Wang Haibin
* @email wanghaibin@qiyi.com
* @date Fri Sep 30 09:17:53 CST 2022
* @brief  测试原子计数相关功能
*/

#include <iostream>
#include <atomic>

using namespace std;

// 测试数值大于65535时轮转情况
void test_ushort_transmigration() {
    std::atomic_ushort xxx(65536);
    unsigned x1 = xxx.load(), x2 = xxx.fetch_add(1), x3 = xxx.fetch_add(1);

    printf("%u, %u, %u\n", x1, x2, x3);
    printf("%u, %u, %u\n", xxx.load(), xxx.fetch_add(1), xxx.fetch_add(1));
}

// 测试compare_exchange_strong函数
void test_compare_exchange_strong() {
    // 1. compare_exchange_strong的expected和ori不同时会将ori的值存储到expected中
    // 2. compare_exchange_strong的expected和ori相同时会用new_val的值修改ori中
    std::atomic_ushort ori(100);
    unsigned short expected = 200, new_val=300;

    if(ori.compare_exchange_strong(expected, new_val)) {
        printf("true ori=%u, expected=%u\n", ori.load(), expected);
    } else {
        printf("false ori=%u, expected=%u\n", ori.load(), expected);
        if(ori.compare_exchange_strong(expected, new_val)) {
            printf("true ori=%u, expected=%u\n", ori.load(), expected);
        }
    }
}

int main()
{
    test_ushort_transmigration();
    test_compare_exchange_strong();
    return 0;
}

